package service.impl;

import dao.BaseDAO;
import dao.UserDAO;
import dao.impl.UserDAOImpl;
import pojo.UserDO;
import service.UserService;
import util.Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserServiceImpl extends BaseDAO implements UserService {
    private UserDAO userDAO = new UserDAOImpl();

    @Override
    public UserDO getByUsernameAndPsw(String username, String psw) {
        return userDAO.getByUsernameAndPsw(username, psw);
    }

    @Override
    public void savemoney(int id, double balance) {
        UserDO user = userDAO.getById(id);
        user.setMoney(user.getMoney() + balance);
        userDAO.update(user);
    }

    @Override
    public void getmoney(int id, double balance) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getMoney() < balance) {
            throw new Exception("余额不足");
        }
        user.setMoney(user.getMoney() - balance);
        userDAO.update(user);
    }

    @Override
    public void modify(int id, String oldpsw, String newpsw, String repsw) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getPassword().equals(oldpsw)) {
            if (repsw.equals(newpsw)) {
                user.setPassword(newpsw);
                userDAO.update(user);
            } else {
                throw new Exception("确认密码错误");
            }
        } else {
            throw new Exception("旧密码错误");
        }
    }

    @Override
    public void trans(int loginid, String othername, double balance) throws Exception {
        UserDO user = userDAO.getById(loginid);
        UserDO other = userDAO.getByUsername(othername);
        if (othername.equals(user.getUsername())) {
            throw new Exception("不能转账给自己");
        }
        if (other == null) {
            throw new Exception("查无此人");
        }
        if (balance > user.getMoney()) {
            throw new Exception("没有那么多钱哦！");
        }
        user.setMoney(user.getMoney() - balance);
        other.setMoney(other.getMoney() + balance);
        userDAO.update(user);
        userDAO.update(other);
    }


}
